package com.jg.blog.controller;

import com.jg.blog.enums.ResultEnum;
import com.jg.blog.pojo.SysUser;
import com.jg.blog.pojo.vo.TokenVO;
import com.jg.blog.utils.Result;
import com.jg.blog.utils.ShiroUtils;
import com.jg.blog.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * @author 16436
 * @version 1.0
 * @date 2021/4/26 16:37
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 登录，返回token
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<TokenVO> login(@RequestBody SysUser sysUser) {
        if (sysUser == null || StringUtils.isBlank(sysUser.getUsername()) || StringUtils.isBlank(sysUser.getPassword())) {
            return new Result<>(ResultEnum.PARAMS_NULL);
        }
        //
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken authenticationToken = new UsernamePasswordToken(sysUser.getUsername(), sysUser.getPassword());
        try {
            subject.login(authenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(ResultEnum.LOGIN_PARAM_ERROR);
        }
        // 登录成功
        Serializable token = subject.getSession().getId();
        return new Result<>(new TokenVO(token));
    }

    /**
     * 获取当前登录用户
     * @return
     */
    @GetMapping("/info")
    public Result<SysUser> info() {
        SysUser sysUser = ShiroUtils.getLoginUser();
        sysUser.setPassword(null);
        return new Result<>(sysUser);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public Result<?> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result<>("退出成功");
    }
}
